//
//  UIColor+RWAdditions.m
//  RWTabbar
//
//  Created by ray on 2021/11/12.
//

#import "UIColor+RWAdditions.h"

@implementation UIColor (RWAdditions)

+ (UIColor *)rw_colorWithHex:(NSInteger)hex{
    return  [UIColor rw_colorWithHex:hex alpha:1.0];
}

+ (UIColor *)rw_colorWithHex:(NSInteger)hex alpha:(CGFloat)alpha{
    CGFloat r = ((hex & 0xFF0000) >> 16) / 255.0;
    CGFloat g = ((hex & 0x00FF00) >> 8) / 255.0;
    CGFloat b = ((hex & 0x0000FF) >> 0) / 255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:alpha];
}

/**
 用于色值字符串
 */
+ (UIColor *)rw_colorWithHexString:(NSString *)hexString{
    return [UIColor rw_colorWithHexString:hexString alpha:1.0];
}

+ (UIColor *)rw_colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    //判断前缀
    if ([cString hasPrefix:@"0X"]) {
        cString = [cString substringFromIndex:2];
    }
    if ([cString hasPrefix:@"#"]) {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6) {
        return [UIColor clearColor];
    }
    
    //从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R G B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:alpha];
}

+ (UIColor *)rw_colorRandom {
    return [UIColor colorWithRed:(arc4random()%256)/255.0f
                           green:(arc4random()%256)/255.0f
                            blue:(arc4random()%256)/255.0f
                           alpha:1.0];
}

@end
